package cn.sc.summer.log.builder;

import cn.hutool.core.util.IdUtil;
import cn.sc.summer.constant.log.SysLog;
import cn.sc.summer.constant.token.TokenConstant;
import cn.sc.summer.exception.exceptions.CommonException;
import cn.sc.summer.exception.util.ip.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 类名：构造者实现类
 *
 * @author a-xin
 * @date 2023/9/5 14:47
 */
@Slf4j
public class LogInfoBuilder extends LogBuilder {

    private final SysLog sysLogInfo = new SysLog();

    /**
     * 构造log发布的基础信息
     */
    @Override
    protected void buildLogInfo() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == requestAttributes) {
            throw new CommonException("The request was exceptional, please try again！");
        }
        HttpServletRequest request = requestAttributes.getRequest();
        sysLogInfo.setId(IdUtil.fastSimpleUUID());
        sysLogInfo.setReqUri(request.getRequestURI());
        sysLogInfo.setReqIp(IPUtil.getIpAddr(request));
        sysLogInfo.setReqMethod(request.getMethod());
        sysLogInfo.setReqUri(request.getRequestURI());
        sysLogInfo.setCreateTime(new Date());
        sysLogInfo.setUpdateTime(new Date());
        sysLogInfo.setReqType(request.getHeader(TokenConstant.REQUEST_TYPE));
    }

    @Override
    protected SysLog build() {
        return sysLogInfo;
    }

}
